<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>路由实现机制</title>
</head>

<body>
    <nav class="nav-box">
        <a href="#/">首页</a>
        <a href="#/product">产品中心</a>
        <a href="#/personal">个人中心</a>
    </nav>
    <div class="view-box"></div>

    <!-- IMPORT JS -->
    <script>
        // 路由容器
        const viewBox = document.querySelector('.view-box');

        // 路由表
        const routes = [{
            path: '/',
            component: '首页的内容'
        }, {
            path: '/product',
            component: '产品中心的内容'
        }, {
            path: '/personal',
            component: '个人中心的内容'
        }];

        // 页面首次加载，默认设置哈希值是“#/”
        location.hash = '/';

        // 监测哈希值变化：拿最新的哈希值去路由表中匹配，把匹配的内容放在容器中渲染
        const handle = () => {
            let hash = location.hash,
                renderText = '';
            hash = hash.slice(1);
            for (let i = 0; i < routes.length; i++) {
                let item = routes[i];
                if (item.path === hash) {
                    renderText = item.component;
                    break;
                }
            }
            viewBox.innerHTML = renderText;
        };
        handle();
        window.addEventListener('hashchange', handle);
    </script>
</body>

</html>